package org.ling.xuan.pipeline;

import org.ling.xuan.channel.CheckChannel;
import org.ling.xuan.context.CheckChannelContext;
import org.ling.xuan.context.CheckPipelineContext;
import org.ling.xuan.handler.CheckExceptionHandler;

import java.util.ArrayList;
import java.util.List;

public class CheckPipeline<R extends CheckPipelineContext> {
    private final List<CheckChannel> checkChannels = new ArrayList<>();

    public CheckPipeline channel(CheckChannel checkChannel) {
        checkChannels.add(checkChannel);
        return this;
    }

    public void start(R pipeContext) {
        CheckChannelContext channelContext = null;
        for (CheckChannel channel : checkChannels) {
            try {

                channelContext = channel.getContext(pipeContext);
                if (channel.match(pipeContext, channelContext)) {
                    channel.execute(pipeContext, channelContext);
                }
            } catch (Exception e) {
                CheckExceptionHandler.handleChannel(pipeContext, channelContext, e);
            }
        }
    }
}
